package org.example.commons.controller;


import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.formula.functions.T;
import org.example.commons.utils.DateUtils;
import org.example.commons.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * web层通用数据处理
 *
 * @author bothin
 */
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 根据传入的数据来导出excel
     * @param response HttpServletResponse
     * @param data 要保存进excel中的数据
     * @param head 要保存进excel中的数据类型
     */
    public void exportExcel(HttpServletResponse response, List data, Class head, String exportName) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode(exportName + System.currentTimeMillis(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), head).autoCloseStream(Boolean.FALSE).sheet(exportName)
                    .doWrite(data);

        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            ResultVO error = ResultVO.error("下载文件失败!! " + e.getMessage());
            response.getWriter().write(error.toString());
        }
    }

}
